package org.jeecg.modules.compilation.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.xcontent.XContentType;
import org.jeecg.common.es.JeecgElasticsearchTemplate;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.compilation.dto.FavouriteSearchDTO;
import org.jeecg.modules.compilation.entity.CiDoc;
import org.jeecg.modules.compilation.entity.CiFavorite;
import org.jeecg.modules.compilation.mapper.CiDocMapper;
import org.jeecg.modules.compilation.mapper.CiFavoriteMapper;
import org.jeecg.modules.compilation.service.ICiDocService;
import org.jeecg.modules.compilation.service.ICiFavoriteService;
import org.jeecg.modules.compilation.util.CommonUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: ci_favorite
 * @Author: jeecg-boot
 * @Date:   2024-03-15
 * @Version: V1.0
 */
@Service
public class CiFavoriteServiceImpl extends ServiceImpl<CiFavoriteMapper, CiFavorite> implements ICiFavoriteService {
    @Autowired
    private ICiDocService ciDocService;
    @Autowired
    public CiDocMapper ciDocMapper;

    @Autowired
    public CiFavoriteMapper ciFavoriteMapper;
    @Autowired
    private JeecgElasticsearchTemplate elasticsearchTemplate;
    /**
     * 获取收藏夹数据
     * @return
     */
    @Override
    public List<CiFavorite> getFavoriteList() {
        //获取用户数据
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getId();

        //根据 用户id 获取数据 列表
        LambdaQueryWrapper<CiFavorite> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CiFavorite::getUserId,userId);
        return this.list(lambdaQueryWrapper);
    }

    /**
     * 获取文件数据
     * @return
     */
    @Override
    public CiDoc getDoc(String documentSn) {
        LambdaQueryWrapper<CiDoc> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CiDoc::getDocumentSn,documentSn);
        ciDocService.getOne(lambdaQueryWrapper);
        return null;
    }

    @Override
    public String updateFavorite(CiFavorite ciFavorite) {
        //获取登录用户信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getId();

        QueryWrapper<CiFavorite> ciFavoriteQueryWrapper = new QueryWrapper<>();
        ciFavoriteQueryWrapper.eq("document_sn",ciFavorite.getDocumentSn()).eq("user_id",userId);
        int delete = ciFavoriteMapper.delete(ciFavoriteQueryWrapper);
        if(delete == 1){
            return "已从收藏夹中移出";
        }

        QueryWrapper<CiDoc> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("document_sn",ciFavorite.getDocumentSn());
        CiDoc note = ciDocMapper.selectOne(queryWrapper);

        ciFavorite.setFavoriteSn(CommonUtil.getSn())
                .setUserId(userId)
                .setDocumentTitle(note.getDocumentTitle());
        BeanUtils.copyProperties(note,ciFavorite,"id","favoriteSn","userId","documentTitle");
        ciFavoriteMapper.insert(ciFavorite);
        return "该制度已加入收藏夹";
    }




    /*
     * 搜索收藏夹
     * **/
    @Override
    public List<CiFavorite> queryList(FavouriteSearchDTO favouriteSearchDTO) throws IOException {
        RestHighLevelClient restHighLevelClient = elasticsearchTemplate.elasticsearchClient();
        SearchRequest request=new SearchRequest("favourite");
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = loginUser.getId();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must((QueryBuilders.matchQuery("userId", userId)));
        String key = favouriteSearchDTO.getKeyword();
        if (key != null && !"".equals(key)) {
            boolQuery.must(QueryBuilders.matchQuery("documentTitle", key));
        }
        boolQuery.must(QueryBuilders.matchQuery("enableFlag","1"));
        request.source().query(boolQuery);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        List<CiFavorite> list = handleResponse(search);
        restHighLevelClient.close();
        return list;
    }

    @Override
    public void deleteById(Long id) {
        try {
            RestHighLevelClient client = elasticsearchTemplate.elasticsearchClient();
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("favourite",id.toString());

            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /*
     * 数据库和索引库的同步
     * */

    @Override
    public void insertById(Long id) throws IOException {
        RestHighLevelClient restHighLevelClient = elasticsearchTemplate.elasticsearchClient();
        CiFavorite c = this.getById(id);
        IndexRequest request = new IndexRequest("document").id(c.getId().toString());
        request.source(JSON.toJSONString(c), XContentType.JSON);
        restHighLevelClient.index(request, RequestOptions.DEFAULT);

    }

    @Override
    public void deleteBatch(List<String> list) {
        try {
            RestHighLevelClient client = elasticsearchTemplate.elasticsearchClient();
            for (String id : list) {
                // 1.准备Request
                DeleteRequest request = new DeleteRequest("favourite",id);
                // 2.发送请求
                client.delete(request, RequestOptions.DEFAULT);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //    /*
//   *  解析请求
//    */
    private List<CiFavorite> handleResponse(SearchResponse search) {
        SearchHits hits = search.getHits();
        long value = hits.getTotalHits().value;
        System.out.println(value + "条数据");
        System.out.println("-------------------------------------");
        SearchHit[] hits1 = hits.getHits();
        List<CiFavorite> list  = new ArrayList<>();
        for (SearchHit hit : hits1) {
            String josn= hit.getSourceAsString();
            CiFavorite ciFavorite = JSON.parseObject(josn, CiFavorite.class);
            list.add(ciFavorite);
        }
        return list;
    }


//    @Override
//    public void omit(String docSn) {
//        //获取登录用户信息
//        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        String userId = loginUser.getId();
//
//        QueryWrapper<CiFavorite> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("document_sn",docSn).eq("user_id",userId);
//        ciFavoriteMapper.delete(queryWrapper);
//
//    }
}
